package com.cysion.study.ui.personal

import android.app.Activity
import android.graphics.Bitmap
import android.text.TextUtils
import android.view.View
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.BasePicActivity
import com.cysion.study.widget.FlowLayoutForPulish
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.http.HttpUtil
import com.cysion.targetfun._subscribe
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import kotlinx.android.synthetic.main.activity_comment_detail.*
import kotlinx.android.synthetic.main.activity_feedback.*
import kotlinx.android.synthetic.main.activity_feedback.fl_pics
import kotlinx.android.synthetic.main.activity_feedback.topbar
import org.json.JSONObject
import java.io.File
import java.util.*

/**
 * 课程详情-点评
 * Created by chu on 2019-07-01.
 */
class CommentActivity : BasePicActivity(), View.OnClickListener {


    override fun getLayoutId(): Int = R.layout.activity_feedback


    private var type = ""
    private var courseId = ""
    private var stuid = ""
    private var depositid = ""
    override fun initView() {
        type = intent.extras.getString("type")
        courseId = intent.extras.getString("courseId")
        stuid = intent.extras.getString("stuid")
        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            //1提交点评、2编辑
            if (type == "1") {
                setTitle("点评")
            } else if (type == "2") {
                setTitle("编辑点评")
                depositid = intent.extras.getString("depositid")
                getComment()
            }
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        tv_submit.setOnClickListener(this)
        initFlowLayoutForPulishListener()

    }

    private fun getComment() {
        Alert.loading(self)
        ApiClient.api.getCommentDetail(depositid, UserCache.token)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    et_comment.setText(it.content)
                    if (!TextUtils.isEmpty(it.content)) {
                        runOnUiThread {
                            et_comment.setSelection(it.content.length)
                        }
                    }
                    /*Glide.with(Box.context).load(it.imageurl)
                        .apply(RequestOptions.placeholderOf(R.mipmap.icon_app))
                        .apply(RequestOptions.bitmapTransform(RoundTransform(6)))
                        .into(iv_img)*/
                    /*selectPics.add(it.imageurl)//把图片添加到list
                    for ((ind,obj) in selectPics.withIndex()) {
                        fl_pics.addLocationPic(ind, false, obj)//显示图片
                    }*/

                    var imgUrl=it.imageurl
                    if (!TextUtils.isEmpty(imgUrl)) {
                        var strs = imgUrl.split(",") as MutableList
                       /* for ((index, obj) in strs.withIndex()) {
                            selectPics.add(obj)
                            fl_pics.addLocationPic(index, false, obj)//显示图片
                        }*/
                        selectPics.addAll(strs)
                        fl_pics.setShowData(false,strs,false,true)
                    }

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }
    }

    private val selectPics = ArrayList<String>()
    private fun initFlowLayoutForPulishListener() {
//        fl_pics.setShow(false)
        fl_pics.setShowData(false,selectPics,false,true)
        fl_pics.setonFlowLayoutForPulishListener(object :
            FlowLayoutForPulish.OnFlowLayoutForPulishListener {
            override fun add() {
                if (selectPics.size >= 9) {
                    ShowToast("最多不能超过9张图片")
                    return
                }
                takePhoto()
            }

            override fun delete(item: FlowLayoutForPulish.Item) {
                selectPics.removeAt(item.index)
            }

            override fun onClick(item: FlowLayoutForPulish.Item) {
                val list = ArrayList<String>()
                list.add(item.path)
//                list.add(getFileUrl(item.path))
                //                PhotoPagerActivity.gotoActivity(_activity, list, 0);//预览大图
            }
        })
    }

    override fun outputBitmap(bitmap: Bitmap?, path: String?) {
        super.outputBitmap(bitmap, path)
        uploadPic(File(path))
    }

    private var index = 0
    private fun uploadPic(headUrl: File) {
        val params = RequestParams()
        params.put("file", headUrl)
        params.put("token", ACache.get(Box.context).getAsString("token"))
        var url = Urls.uploadPicture
        println("上传图片接口==" + url)
        HttpUtil.post1(url, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(
                statusCode: Int,
                headers: Array<out org.apache.http.Header>?,
                response: JSONObject?
            ) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                try {
                    if (response?.getString("code") == "0") {
                        println("上传图片返回=${response.getString("data")}")
//                        var obj: String? = response.getString("data")
                        selectPics.add(response.getString("data"))//把图片添加到list
                        if (selectPics.size > 0) {
                            index=selectPics.size+1
                        }
//                        fl_pics.addLocationPic(index, false, response.getString("data"))//显示图片
                        fl_pics.setShowData(false,selectPics,false,true)
                        index++
                    } else {
                        ShowToast("上传失败")
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    Alert.close()
//                    ShowDialog.dissmiss()
                }
            }

            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(
                statusCode: Int,
                headers: Array<out org.apache.http.Header>?,
                responseString: String?,
                throwable: Throwable?
            ) {
                super.onFailure(statusCode, headers, responseString, throwable)
                println("####上传失败" + statusCode + "##=" + responseString)
                Alert.close()
            }
        })
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_submit -> {
                var content = et_comment.text.toString().trim()
                if (TextUtils.isEmpty(content)) {
                    ShowToast("请输入点评内容")
                    return
                }
                var imgUrl = ""
                var sb = StringBuilder()
                val pics = ArrayList<String>()
                if (selectPics != null && selectPics.size > 0) {
                    for (im in selectPics) {
                        sb.append("," + im)
                    }
                    if (sb.length > 0) {
                        sb.deleteCharAt(0)
                    }
                    imgUrl = sb.toString()
                    pics.add(imgUrl)
                    println("###图片地址=" + imgUrl)
                }

                Alert.loading(this)
                ApiClient.api.commintComment(
                    courseId,
                    stuid,
                    content,
                    imgUrl,
                    UserCache.token
                )
                    .compose(BaseResponseRx.validateToMain())
                    ._subscribe {
                        _onNext {
                            Alert.close()
                            ShowToast("提交成功")
                            setResult(Activity.RESULT_OK)
                            finish()
                        }
                        _onError {
                            Alert.close()
                            ShowToast(ErrorHandler.handle(it).errorMsg)
                        }
                    }

            }
        }

    }


    override fun closeMvp() {
    }
}